package com.xxx.mall.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxx.mall.constant.EnableStatusEnum;
import com.xxx.mall.constant.IsDeletedEnum;
import com.xxx.mall.converter.CategoryConverter;
import com.xxx.mall.dto.CategoryDTO;
import com.xxx.mall.exception.MallException;
import com.xxx.mall.mapper.CategoryMapper;
import com.xxx.mall.model.Category;
import com.xxx.mall.service.CategoryService;
import com.xxx.mall.vo.CategoryVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 分类信息 服务实现类
 * </p>
 *
 * @author 邢晨旭
 * @since 2023-11-15
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Resource
    CategoryConverter categoryConverter;

    @Override
    public List<CategoryVO> queryList(Long shopId) {
        return baseMapper.list(shopId);
    }

    @Override
    public void updateCategoryById(CategoryDTO categoryDTO) {
        if (categoryDTO.getCategoryId().equals(categoryDTO.getParentId())) {
            throw new MallException("父分类不能是自己");
        }
        checkCategory(categoryDTO);
        baseMapper.updateById(categoryConverter.toCategory(categoryDTO));
    }


    @Override
    public void deleteById(Long id) {
        Category category = baseMapper.selectById(id);
        if (IsDeletedEnum.DELETED.value().equals(category.getIsDeleted())) {
            return;
        }
        if (EnableStatusEnum.DISABLE.value().equals(category.getStatus())) {
            //todo 关联分类不能删除
            //分类关联的有属性的不能删除
            //分类关联的有品牌的不能删除
            //分类关联的有商品的不能删除
            //只能删除三级分类和没有子分类的分类
            int count = baseMapper.existChildCategory(id);
            if (category.getLevel() == 2 || baseMapper.existChildCategory(id) == 0) {
                //可以直接删除
                baseMapper.removeById(id);
            }
            return;
        }
        throw new MallException("分类已被使用，不能删除");

    }

    @Override
    public void saveCategory(CategoryDTO categoryDTO) {
        checkCategory(categoryDTO);
        Category category = categoryConverter.toCategory(categoryDTO);
        baseMapper.insert(category);
    }

    @Override
    public CategoryVO queryById(Long id) {
        Category category = baseMapper.selectById(id);
        if (category == null || IsDeletedEnum.DELETED.value().equals(category.getIsDeleted())) {
            throw new MallException("分类不存在");
        }
        return categoryConverter.toCategoryVO(category);
    }

    @Override
    public void categoryEnableOrDisable(Long id, Integer status) {
        //
    }

    @Override
    public List<CategoryVO> queryTreeList(Long shopId) {
        List<CategoryVO> list = baseMapper.list(shopId);
        //根据父id分组
        Map<Long, List<CategoryVO>> listMap = list.stream()
                .sorted(Comparator.comparingInt(CategoryVO::getSeq))
                .collect(Collectors.groupingBy(CategoryVO::getParentId));
        List<CategoryVO> result = list.stream()
                .peek(categoryVO -> categoryVO.setChildren(listMap.get(categoryVO.getCategoryId())))
                //默认升序
                .filter(categoryVO -> categoryVO.getParentId().equals(0L))
                .sorted(Comparator.comparingInt(CategoryVO::getSeq))
                //转换成list
                .collect(Collectors.toList());
        //转换成树形结构返回
        return result;
    }

    @Override
    public List<CategoryVO> queryListByLevel(Long shopId, Integer level) {
        return baseMapper.ListByLevel(shopId, level);
    }

    @Override
    public List<CategoryVO> queryListByParentId(Long shopId, Long parentId) {
        return baseMapper.ListByParentId(shopId, parentId);
    }

    @Override
    public CategoryVO queryCategoryById(Long id) {
        return categoryConverter.toCategoryVO(baseMapper.selectById(id));
    }

    @Override
    public List<CategoryVO> queryPlatformFirstCategory(long platformShopId, int level) {
        return baseMapper.ListByLevel(platformShopId, level);
    }

    @Override
    public List<Long> queryAllParentId(Long categoryId) {
        return baseMapper.queryAllParentId(categoryId);
    }

    private void checkCategory(CategoryDTO categoryDTO) {
        if (categoryDTO.getParentId() != 0) {
            Category categoryP = baseMapper.selectById(categoryDTO.getParentId());
            if (categoryP == null && IsDeletedEnum.DELETED.value().equals(categoryP.getIsDeleted())) {
                throw new MallException("父分类不存在");
            }
            Integer level = categoryP.getLevel();
            if (level > 2 || level + categoryDTO.getLevel() > 3) {
                throw new MallException("分类级别不正确");
            }
        }
        int count = baseMapper.existCategoryName(categoryDTO.getShopId(), categoryDTO.getCategoryId(), categoryDTO.getName());
        if (count > 0) {
            throw new MallException("分类名称已存在");
        }
    }

}
